package com.strive.security;

import cn.hutool.json.JSONUtil;
import com.strive.common.exception.CaptchaException;
import com.strive.common.result.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: strivePeng
 * @CreateTime: 2024年03月18日
 * @Description: 登录请求失败的处理器
 **/
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    /**
     * 重写方法 返回的数据格式
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8"); // 设置编码
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        // 判断错误类型实现消息的返回
        String errorMessage;
        if (e instanceof BadCredentialsException) {
            errorMessage = "用户名或密码错误";
        } else if (e instanceof CaptchaException) {
            errorMessage = "验证码错误";
        } else {
            errorMessage = "认证失败";
        }

        Result result = Result.fail(errorMessage);
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
